Page({
  data: {
    orderId: '',
    userName: '用户',
    rating: 0,
    content: '',
    anonymous: false,
    canSubmit: false,
    contentLength: 0,
    minContentLength: 8,
    isReviewed: false
  },
  onLoad(options) {
    this.setData({ orderId: options.orderId || '' });
    // 加载订单详情，判断是否已评价
    const app = getApp();
    app.request({
      url: `/api/orders/${options.orderId}`,
      method: 'GET'
    }).then(res => {
      const order = res.data;
      // 如果已评价，禁用按钮并显示提示
      if (order.review_content) {
        this.setData({
          rating: order.review_rating || 0,
          content: order.review_content || '',
          canSubmit: false, // 禁用按钮
          contentLength: order.review_content ? order.review_content.length : 0,
          isReviewed: true // 设置已评价
        });
      }
    });
    // 可根据实际获取用户昵称
  },
  onStarTap(e) {
    const rating = e.currentTarget.dataset.index + 1;
    this.setData({ rating }, this.checkCanSubmit);
  },
  onContentInput(e) {
    const content = e.detail.value;
    const contentLength = content.length;
    this.setData({ 
      content,
      contentLength
    }, this.checkCanSubmit);
  },
  onAnonymousChange(e) {
    this.setData({ anonymous: e.detail.value.length > 0 });
  },
  checkCanSubmit() {
    this.setData({
      canSubmit: this.data.rating > 0 && this.data.content.trim().length >= this.data.minContentLength
    });
  },
  submitReview() {
    const { orderId, rating, content, anonymous } = this.data;
    if (rating === 0) {
      wx.showToast({ 
        title: '请先选择星级', 
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (content.trim().length < this.data.minContentLength) {
      wx.showToast({ 
        title: `评价内容不少于${this.data.minContentLength}个字`, 
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.showLoading({ 
      title: '提交中...',
      mask: true
    });
    
    const app = getApp();
    wx.request({
      url: `${app.globalData.baseUrl}/api/orders/${orderId}/review`,
      method: 'POST',
      data: { rating, content, anonymous },
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          wx.showToast({ 
            title: '评价成功', 
            icon: 'success',
            duration: 2000
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        } else {
          console.error('提交评价失败，后端响应:', res);
          wx.showToast({ 
            title: res.data && res.data.message ? res.data.message : '提交失败', 
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ 
          title: '网络错误', 
          icon: 'none',
          duration: 2000
        });
      }
    });
  }
}); 